﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

namespace HardStyle.SimpleEventBus.Registration
{
    internal static class HandlerRegistrar
    {
        public static void Registrar(IServiceCollection services, IEnumerable<Assembly> handlerAssemblies, SimpleEventBusServiceConfiguration configuration)
        {
            //Assembly de duplication
            handlerAssemblies = handlerAssemblies.Distinct().ToArray();

            //Scan Event handler
            var handlerImps = handlerAssemblies
                .SelectMany(x => x.GetTypes())
                .Where(x => x.IsAbstract == false && x.GetInterface(typeof(ISimpleEventHandle<>).FullName) != null);

            //Exclude handlers that need to be excluded
            handlerImps = handlerImps.Except(configuration.ExcludeHandleTypes);

            //Register Handler Service
            foreach (var handlerType in handlerImps)
            {
                var eventType = handlerType.GetInterface(typeof(ISimpleEventHandle<>).FullName).GetGenericArguments()[0];
                services.AddTransient(typeof(ISimpleEventHandle<>).MakeGenericType(eventType), handlerType);
            }

        }

    }
}
